<?php
//首先读取前端用户提交的数据，并进行必要的验证
$username = trim($_POST['username']);  //trim  过滤  空格。。。。
$password = $_POST['password'];
$r_password = $_POST['r_password'];
$sex = $_POST['sex'];
$email = $_POST['email'];
$fav = @implode(',', $_POST['fav']); //explode   @用于屏蔽错误

//表单验证
if ($username == "") {
    echo "<script>alert('用户名必须填写！');history.back();</script>";
    exit();
}
if ($password == "") {
    echo "<script>alert('密码必须填写！');history.back();</script>";
    exit();
}
if ($r_password == "") {
    echo "<script>alert('确认密码必须填写！');history.back();</script>";
    exit();
}
if ($r_password != $password) {
    echo "<script>alert('密码和确认密码必须相等！');history.back();</script>";
    exit();
}

//加密
$password = md5($password);

//引入数据库连接文件
include_once "conn.php";

//判断用户名是否占用
$sql = "select * from userinfo where username='$username'";
$result = mysqli_query($conn, $sql);
$number = mysqli_num_rows($result);

//如果此用户名已经被占用，则$number=1，否则$number=0
if ($number) {
    echo "<script>alert('此用户名已经被占用!');history.back();</script>";
} else {
    //此用户名有效
    //接下来，将数据插入表，完成注册
    $sql = "insert into userinfo(username,password,email,sex,fav) values ('$username','$password','$email','$sex','$fav')";
    $result = mysqli_query($conn, $sql);
//    echo mysqli_error($conn);
//    exit();
    if ($result) {
        echo "<script>alert('注册成功！');location.href='index.php';</script>";
    } else {
        echo "<script>alert('注册失败！');history.back();</script>";
    }
}